#!/usr/bin/env bash
#
# Travis CI Scripts
# Copyright (C) 2018-2020 by Thomas Dreibholz
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Contact: dreibh@iem.uni-due.de

# Bash options:
set -e


maxTrials=3
pause=10
while [ $# -gt 0 ] ; do
   case "$1" in
      -t|--tries)
          maxTrials="$2"
          shift 2
         ;;
      -p|--pause)
          pause="$2"
          shift 2
         ;;
      --)
         shift
         break
         ;;
      *)
         echo >&2 "Usage: $0 [-t|--trials max_trials] [-p|--pause seconds] -- command ..."
         exit 1
        ;;
   esac
done


attempts=1
result=1
command="$@"
while [[ ${result} -ne 0 && ${attempts} -le ${maxTrials} ]] ; do
   if [ ${attempts} -gt 1 ] ; then
      echo "Sleeping ${pause}s ..."
      sleep ${pause}
   fi
   echo "Trying ${attempts}/${maxTrials}: ${command}"
   bash -c "${command}" && result=$? || result=$?
   if [ ${result} -eq 127 ] ; then
      # Command not found => no need for a retry!
      exit ${result}
   elif [ ${result} -ne 0 ] ; then
      # Attempt failed
      let attempts=${attempts}+1
   fi
done


exit ${result}
